package task

import ext.log
import manager.AppManager
import manager.AsyncTask
import manager.NetworkManager
import manager.StatusManager
import popup.DeliveryWindow
import popup.PayWindow


class UpdateStatusTask : Runnable {

    private var networkOutageCount = 0 // 断网计数
    private var statusCount = -1

    companion object {
        const val NETWORK_OUTAGE_TIME_OUT =  30 * 1 / 3 // 4H
    }

    override fun run() {
        try {
            AppManager.checkApplication()

            val content = if (statusCount == StatusManager.StatusCount) {
                StatusManager.toJsonWith3("666")
            } else {
                StatusManager.toJsonWith3()
            }
            log(content, "3分钟一次上传数据")
            val ret = NetworkManager.update3StatusToServer(content)
            log("--$ret", "3分钟一次上传数据返回")
            networkOutageCount = 0
        } catch (e: Exception) {
            e.printStackTrace()
            networkOutageCount++
        }

        statusCount = StatusManager.StatusCount
        AsyncTask.postDelayed(this, 3 * 60 * 1000)

        if (networkOutageCount > NETWORK_OUTAGE_TIME_OUT) {
            if (DeliveryWindow.isShow || PayWindow.isShow) {
                return
            }
            log("断网超时开始重启")
            AppManager.resetApp()
        }
    }
}
